// AI配置管理模块
class AIConfigManager {
  constructor() {
    this.storageKey = 'zhipu_ai_config';
    this.config = this.loadConfig();
  }

  // 从本地存储加载配置
  loadConfig() {
    try {
      const stored = localStorage.getItem(this.storageKey);
      if (stored) {
        return JSON.parse(stored);
      }
    } catch (error) {
      console.warn('加载AI配置失败:', error);
    }
    
    return {
      apiKey: '',
      model: 'glm-4.5-flash',
      temperature: 0.1,
      maxTokens: 500,
      enabled: false
    };
  }

  // 保存配置到本地存储
  saveConfig(config) {
    try {
      this.config = { ...this.config, ...config };
      localStorage.setItem(this.storageKey, JSON.stringify(this.config));
      return true;
    } catch (error) {
      console.error('保存AI配置失败:', error);
      return false;
    }
  }

  // 获取当前配置
  getConfig() {
    return { ...this.config };
  }

  // 设置API密钥
  setApiKey(apiKey) {
    return this.saveConfig({ apiKey: apiKey.trim() });
  }

  // 获取API密钥
  getApiKey() {
    return this.config.apiKey;
  }

  // 检查是否已配置
  isConfigured() {
    return !!(this.config.apiKey && this.config.apiKey.trim());
  }

  // 启用/禁用AI功能
  setEnabled(enabled) {
    return this.saveConfig({ enabled });
  }

  // 检查是否启用
  isEnabled() {
    return this.config.enabled && this.isConfigured();
  }

  // 清除配置
  clearConfig() {
    try {
      localStorage.removeItem(this.storageKey);
      this.config = {
        apiKey: '',
        model: 'glm-4.5-flash',
        temperature: 0.1,
        maxTokens: 500,
        enabled: false
      };
      return true;
    } catch (error) {
      console.error('清除AI配置失败:', error);
      return false;
    }
  }

  // 验证API密钥格式
  validateApiKey(apiKey) {
    if (!apiKey || typeof apiKey !== 'string') {
      return { valid: false, message: 'API密钥不能为空' };
    }

    const trimmed = apiKey.trim();
    if (trimmed.length < 10) {
      return { valid: false, message: 'API密钥长度不足' };
    }

    // 智谱AI的API密钥通常以特定格式开始
    if (!trimmed.includes('.')) {
      return { valid: false, message: 'API密钥格式不正确' };
    }

    return { valid: true, message: 'API密钥格式正确' };
  }

  // 创建配置界面
  createConfigUI() {
    const configContainer = document.createElement('div');
    configContainer.className = 'ai-config-container';
    configContainer.innerHTML = `
      <div class="ai-config-panel">
        <h3>智谱AI配置</h3>
        <div class="config-item">
          <label for="ai-api-key">API密钥:</label>
          <input type="password" id="ai-api-key" placeholder="请输入智谱AI API密钥" value="${this.config.apiKey}">
          <button id="toggle-api-key" type="button">👁️</button>
        </div>
        <div class="config-item">
          <label>
            <input type="checkbox" id="ai-enabled" ${this.config.enabled ? 'checked' : ''}>
            启用AI正则生成
          </label>
        </div>
        <div class="config-actions">
          <button id="save-ai-config" class="save-btn">保存配置</button>
          <button id="test-ai-config" class="test-btn">测试连接</button>
          <button id="clear-ai-config" class="clear-btn">清除配置</button>
        </div>
        <div id="config-status" class="config-status"></div>
        <div class="config-help">
          <p>💡 获取API密钥：</p>
          <ol>
            <li>访问 <a href="https://open.bigmodel.cn/" target="_blank">智谱AI开放平台</a></li>
            <li>注册并登录账号</li>
            <li>在控制台创建API密钥</li>
            <li>将密钥粘贴到上方输入框</li>
          </ol>
        </div>
      </div>
    `;

    // 绑定事件
    this.bindConfigEvents(configContainer);
    
    return configContainer;
  }

  // 绑定配置界面事件
  bindConfigEvents(container) {
    const apiKeyInput = container.querySelector('#ai-api-key');
    const toggleBtn = container.querySelector('#toggle-api-key');
    const enabledCheckbox = container.querySelector('#ai-enabled');
    const saveBtn = container.querySelector('#save-ai-config');
    const testBtn = container.querySelector('#test-ai-config');
    const clearBtn = container.querySelector('#clear-ai-config');
    const statusDiv = container.querySelector('#config-status');

    // 切换密钥显示/隐藏
    toggleBtn.addEventListener('click', () => {
      const type = apiKeyInput.type === 'password' ? 'text' : 'password';
      apiKeyInput.type = type;
      toggleBtn.textContent = type === 'password' ? '👁️' : '🙈';
    });

    // 保存配置
    saveBtn.addEventListener('click', () => {
      const apiKey = apiKeyInput.value.trim();
      const enabled = enabledCheckbox.checked;

      if (enabled && !apiKey) {
        this.showStatus(statusDiv, '请先输入API密钥', 'error');
        return;
      }

      if (apiKey) {
        const validation = this.validateApiKey(apiKey);
        if (!validation.valid) {
          this.showStatus(statusDiv, validation.message, 'error');
          return;
        }
      }

      const success = this.saveConfig({ apiKey, enabled });
      if (success) {
        this.showStatus(statusDiv, '配置保存成功', 'success');
        
        // 通知其他组件配置已更新
        window.dispatchEvent(new CustomEvent('aiConfigUpdated', {
          detail: { apiKey, enabled }
        }));
      } else {
        this.showStatus(statusDiv, '配置保存失败', 'error');
      }
    });

    // 测试连接
    testBtn.addEventListener('click', async () => {
      const apiKey = apiKeyInput.value.trim();
      if (!apiKey) {
        this.showStatus(statusDiv, '请先输入API密钥', 'error');
        return;
      }

      this.showStatus(statusDiv, '正在测试连接...', 'info');
      
      try {
        // 创建临时的AI服务实例进行测试
        const testService = new ZhipuAIService();
        testService.setApiKey(apiKey);
        
        // 使用简单的测试文本
        const testResult = await testService.generateRegex('test123', '');
        
        if (testResult) {
          this.showStatus(statusDiv, '连接测试成功！', 'success');
        } else {
          this.showStatus(statusDiv, '连接测试失败', 'error');
        }
      } catch (error) {
        this.showStatus(statusDiv, `连接测试失败: ${error.message}`, 'error');
      }
    });

    // 清除配置
    clearBtn.addEventListener('click', () => {
      if (confirm('确定要清除所有AI配置吗？')) {
        const success = this.clearConfig();
        if (success) {
          apiKeyInput.value = '';
          enabledCheckbox.checked = false;
          this.showStatus(statusDiv, '配置已清除', 'success');
          
          // 通知其他组件配置已清除
          window.dispatchEvent(new CustomEvent('aiConfigUpdated', {
            detail: { apiKey: '', enabled: false }
          }));
        } else {
          this.showStatus(statusDiv, '清除配置失败', 'error');
        }
      }
    });
  }

  // 显示状态信息
  showStatus(statusDiv, message, type) {
    statusDiv.textContent = message;
    statusDiv.className = `config-status ${type}`;
    
    // 3秒后清除状态
    setTimeout(() => {
      statusDiv.textContent = '';
      statusDiv.className = 'config-status';
    }, 3000);
  }
}

// 导出配置管理器
window.AIConfigManager = AIConfigManager;